package com.binbai.register;

import com.alibaba.fastjson.JSON;
import com.binbai.db.DB;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.BufferedReader;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;

@WebServlet("/register")
public class RegisterServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 设置请求和响应的编码格式
        request.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=UTF-8");
        String username = request.getParameter("username");
        // 读取请求体中的JSON数据
        StringBuilder sb = new StringBuilder();
        BufferedReader reader = request.getReader();
        String line;
        while ((line = reader.readLine()) != null) {
            sb.append(line);
        }
        String requestBody = sb.toString();

        // 将JSON数据转换为RegistrationInfo对象
        RegistrationInfo registrationInfo = JSON.parseObject(requestBody, RegistrationInfo.class);

        // 验证注册信息（例如，检查用户名是否已存在）
        if (isUsernameExists(registrationInfo.getUsername())) {
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("result", "error");
            errorResponse.put("message", "用户名已存在");
            response.getWriter().write(JSON.toJSONString(errorResponse));
            return;
        }

        // 插入注册信息到数据库
        if (insertRegistrationInfo(registrationInfo)) {
            Map<String, String> successResponse = new HashMap<>();
            successResponse.put("result", "success");
            response.getWriter().write(JSON.toJSONString(successResponse));
        } else {
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("result", "error");
            errorResponse.put("message", "注册失败");
            response.getWriter().write(JSON.toJSONString(errorResponse));
        }
    }

    private boolean isUsernameExists(String username) {
        try (Connection connection = DB.getConnection();
             PreparedStatement statement = connection.prepareStatement("SELECT * FROM t_user WHERE name = ?")) {
            statement.setString(1, username);
            try (java.sql.ResultSet rs = statement.executeQuery()) {
                return rs.next();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return false;
    }

    private boolean insertRegistrationInfo(RegistrationInfo registrationInfo) {
        try (Connection connection = DB.getConnection();
             PreparedStatement statement = connection.prepareStatement("INSERT INTO t_user (name, pass, beizhu) VALUES (?, ?, ?)")) {
            statement.setString(1, registrationInfo.getUsername());
            statement.setString(2, registrationInfo.getPassword());
            statement.setString(3, registrationInfo.getRemark());
            int rowsAffected = statement.executeUpdate();
            return rowsAffected > 0;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return false;
    }
}
